#coding: utf-8

from MySQLdb import connect,IntegrityError


def calculate_avgPrice ():
    conn=connect(user='cheng3',passwd='123456',db='cheng3',host='localhost')
    cursor=conn.cursor()
    cursor.execute('set names utf8')
    cursor.execute('set character set utf8')
    cursor.execute('select postDate,truncate(avg(price),2) from buildingprice group by postDate')
    tus=cursor.fetchall()
    for tu in tus:
        try:
            cursor.execute('insert into avgprice (housingProject_id,postDate,price) values (1,%s,%s)',(tu[0],tu[1]))
        except IntegrityError:
            pass
        else:
            print tu[0],':',tu[1]

    cursor.execute('select count(*) from building')
    totalBuilding=cursor.fetchone()[0]
    cursor.execute('select count(*) from buildingprice')
    totalBuildingPrice=cursor.fetchone()[0]
    print 'totalBuilding =',totalBuilding
    print 'totalBuildingPrice =',totalBuildingPrice

if __name__=='__main__':
    calculate_avgPrice()